//
//  KYZXWebVC.m
//  KuYouZiXun
//
//  Created by lanou on 15/8/6.
//  Copyright (c) 2015年 lanou. All rights reserved.
//
#define kURL @"http://appapi.gamersky.com/v1/article"

#import "KYZXWebVC.h"

#import "KYZXScreen.h"

#import "NSString+Html.h"

#import "LJRequestManagerBlock.h"

#import "KYZXWebModel.h"

#import "KYZXUserInfo.h"

#import "KYZXWebMoreView.h"

#import "KYZXWebBottomView.h"

#import "UIImageView+WebCache.h"
@interface KYZXWebVC ()<UIWebViewDelegate, UIGestureRecognizerDelegate, KYZXWebBottomViewDelegate>

@property (strong, nonatomic)UIWebView *webView;

@property (strong, nonatomic)NSDictionary *dict;//参数

@property (strong, nonatomic)KYZXWebModel *dataSource;//数据

@property (strong, nonatomic)KYZXWebMoreView *moreView;

@property (strong, nonatomic)UIView *bgView;

@property (strong, nonatomic)UIImageView *imgView;
@end

@implementation KYZXWebVC




- (instancetype)init
{
    if (self = [super init]) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (NSDictionary *)dict
{
    if(_dict == nil){
        _dict = @{@"generalId":self.generalId,@"pageIndex":@1};
    }
    return _dict;
}

- (void)requestData:(NSDictionary *)dic
{
    [LJRequestManagerBlock manager:POST requestWith:kURL dic:dic finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSDictionary *resultDict = dict[@"result"];
        self.dataSource = [[KYZXWebModel alloc] init];
        [self.dataSource setValuesForKeysWithDictionary:resultDict];
        [self createWebView];
    } error:^(NSError *error) {
    }];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.leftButton setImage:[UIImage imageNamed:@"gsContentToolBarView_PrevPage.night"] forState:UIControlStateNormal];
    [self createRightButton];
    self.view.backgroundColor = [KYZXUserInfo standardKYZXUserInfo].backgroundColor;
    [self requestData:self.dict];
    //解决 自己写的屏幕边缘手势与 navigationController的边缘手势冲突
    [self.edgePan requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
    [self createMoreView];
    [self createBottomView];
}


- (void)createRightButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(SCREEN_WIDTH - 44, 0, 44, 44);
    [button setImage:[UIImage imageNamed:@"content_moreButton"] forState:UIControlStateNormal];
    [self.topBarView addSubview:button];
    [button addTarget:self action:@selector(doTapRightButton) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)createMoreView
{
    self.moreView = [KYZXWebMoreView instanceView];
    _moreView.frame = self.view.bounds;
    _moreView.hidden = YES;
    [self.moreView getUserInfo];
    [self.view addSubview:_moreView];
}


- (void)doTapRightButton
{
    self.moreView.hidden = NO;
}
//- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    NSLog(@"网页加载完毕");
////网页图片适应屏幕宽度
//    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"var script = document.createElement('script');"
//                                                     "script.type = 'text/javascript';"
//                                                     "script.text = \"function ResizeImages() { "
//                                                     "var myimg,oldwidth;"
//                                                     "var maxwidth = 300.0;" // UIWebView中显示的图片宽度
//                                                     "for(i=0;i <document.images.length;i++){"
//                                                     "myimg = document.images[i];"
//                                                     "if(myimg.width > maxwidth){"
//                                                     "oldwidth = myimg.width;"
//                                                     "myimg.width = maxwidth;"
//                                                     "}"
//                                                     "}"
//                                                     "}\";"
//                                                     "document.getElementsByTagName('head')[0].appendChild(script);"]
//     ];
//    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
//    
//}

- (void)createWebView
{
    NSString *htmlStr = self.dataSource.newsContent;
    //原先不能使用的原因第一是没有头文件,第二是没有设置类,所以我们给原先的html添加的下面的一段东西
    htmlStr = [NSString stringWithFormat:@"<head> </head> <article class=\"typo container\"><div id=\"body\" class=\"fontsizetwo\"><h1 class=\"heading\" id=\"gsTemplateContent_Title\">%@</h1><span class=\"info\" id=\"gsTemplateContent_Subtitle\">作者:%@  来源:%@  时间:%@</span><div class=\"bar\">----------</div>%@",self.dataSource.title,self.dataSource.author,self.dataSource.source,self.dataSource.dateTime,htmlStr];
    NSString *str = [NSString importStyleWithHtmlString:htmlStr];
    self.webView = [[UIWebView alloc] initWithFrame:self.contentView.bounds];
    [self.webView loadHTMLString: str baseURL:[NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]];
    //这个属性会让原网页缩放,但是不是我们想要的效果
    //self.webView.scalesPageToFit = YES;
    _webView.delegate = self;
    
    _webView.opaque = NO; //不设置这个值 页面背景始终是白色
    _webView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:_webView];
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"test" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil]];
}


-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_webView stringByEvaluatingJavaScriptFromString:@"setImageClickFunction()"];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSString *path=[[request URL] absoluteString];
    
    NSLog(@"%@",path);
    return YES;
}





- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    self.view.backgroundColor = [KYZXUserInfo standardKYZXUserInfo].backgroundColor;
    self.topBarView.backgroundColor = [KYZXUserInfo standardKYZXUserInfo].backgroundColor;
    [self changeColor:[[NSUserDefaults standardUserDefaults] objectForKey:@"配色方案"]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


//改变颜色
- (void)changeColor:(NSString *)str
{
    if ([str isEqualToString:@"夜间模式"]) {
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'lightGray'"];
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#2E2E2E'"];
    }
    else {
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'black'"];
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='white'"];
    }
}

- (void)doTapLeftButton:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 创建底栏视图

- (void)createBottomView
{
    KYZXWebBottomView *bottomView = [KYZXWebBottomView instanceView];
    bottomView.frame = CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49);
    bottomView.delegate = self;
    [self.view addSubview:bottomView];
}

- (void)collect:(id)object
{
    UIButton *button = (UIButton *)object;
    button.selected = !button.selected;
    NSLog(@"收藏");
}

- (void)share
{
    NSLog(@"分享");
}

- (void)comment
{
    NSLog(@"评论");
}
@end
